var wUtils = require('../../utils/wechatRequest.js');

Page({
   data: {
      mobile: '',
      verifyCode: '',
      sendBtnName: "获取验证码",
      timer: '',
      countDownNum: '60',
      sendBtnDisable: true
   },
   onLoad: function() {

   },
   bindMobile: function(e) {
      this.setData({
         mobile: e.detail.value
      });
   },
   bindVerifyCode: function(e) {
      this.setData({
         verifyCode: e.detail.value
      });
   },
   sendVerifyCode: function() {
      var that = this;
      if (that.data.mobile == ""){
         wx.showToast({
            title: '请输入手机号!',
            icon: 'none'
         })
         return;
      }
      if (!that.data.sendBtnDisable){
         wx.showToast({
            title: '短信已发送，请等候！',
            icon: 'none'
         })
         return;
      }
      wUtils.doGet('/app/user/verifyCode/' + that.data.mobile, null, function(res) {
         if (res.code == 0) {
            console.log('success');
            that.countDown();
            that.setData({
               sendBtnDisable: false
            })
         } else {
            console.log(res.msg);
         }
      });
   },

   countDown: function() {
      let that = this;
      let countDownNum = that.data.countDownNum;
      that.setData({
         timer: setInterval(function() {
            countDownNum--;
            console.log(countDownNum);
            that.setData({
               countDownNum: countDownNum,
               sendBtnName: (countDownNum) + "秒后请重试"
            });

            if (countDownNum == 0) {
               clearInterval(that.data.timer);
               that.setData({
                  sendBtnName: "重新获取"
               });
            }
         }, 1000)
      })
   },

   bindsubmit: function() {
      var that = this;
      if (that.data.mobile == "") {
         wx.showToast({
            title: '请输入手机号!',
            icon: 'none'
         })
         return;
      }
      if (that.data.verifyCode == "") {
         wx.showToast({
            title: '请输入验证码!',
            icon: 'none'
         })
         return;
      }
      var postData = {};
      postData.mobile = that.data.mobile;
      postData.verifyCode = that.data.verifyCode;
      wUtils.doPost('/app/user/bind/mobile', postData, function(res) {
         if (res.code == 0) {
            console.log('绑定成功.');
            clearInterval(that.data.timer);
            // 需要重新设置user.js的userInfo属性, 绑定成功之后应该刷新积分
            wx.switchTab({
               url: '../user/user'
            });
         } else {
            console.log('绑定失败');
            console.log('失败原因:' + res.msg);
         }
      });
   }
})